import tkinter as tk
from tkinter import messagebox, Toplevel, Scrollbar, Listbox, Label
import mysql.connector


class GoodsManagement:
    def __init__(self):
        self.top = Toplevel()
        self.top.title("商品管理")
        self.top.geometry("400x400")

        # 创建输入框变量
        self.x1 = tk.StringVar()
        self.x2 = tk.StringVar()
        self.x3 = tk.StringVar()
        self.x4 = tk.StringVar()
        self.x5 = tk.StringVar()
        self.x6 = tk.StringVar()

        self.setup_database()  # 确保在需要之前调用此方法
        self.setup_entryframe()

        # 创建按钮
        tk.Button(self.top, text="查询", command=self.query_goods).pack(side=tk.LEFT, padx=5, pady=5)
        tk.Button(self.top, text="增加", command=self.add_goods).pack(side=tk.LEFT, padx=5, pady=5)
        tk.Button(self.top, text="删除", command=self.delete_goods).pack(side=tk.LEFT, padx=5, pady=5)
        tk.Button(self.top, text="修改", command=self.update_goods).pack(side=tk.LEFT, padx=5, pady=5)
        tk.Button(self.top, text="退出程序", command=self.top.destroy).pack(side=tk.LEFT, padx=5, pady=5)  # 新增退出按钮

        # 创建滚动条和列表框
        self.scrollbar = Scrollbar(self.top)
        self.scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.listbox = Listbox(self.top, yscrollcommand=self.scrollbar.set)
        self.listbox.pack(fill=tk.BOTH, expand=True)
        self.scrollbar.config(command=self.listbox.yview)

        # 初始查询商品信息
        self.query_goods()
        self.top.mainloop()

    def setup_entryframe(self):
        # 创建一个表单框架
        self.form_frame = tk.Frame(self.top)
        self.form_frame.pack(pady=10)  # 增加一些内边距

        # 商品编号输入框（必填）
        l1 = Label(self.form_frame, text="商品编号（必填）:")
        l1.pack(side=tk.LEFT, padx=5, pady=5)
        tk.Entry(self.form_frame, textvariable=self.x1).pack(side=tk.LEFT, padx=5, pady=5)

        # 商品名称输入框
        l2 = Label(self.form_frame, text="商品名称:")
        l2.pack(side=tk.LEFT, padx=5, pady=5)
        tk.Entry(self.form_frame, textvariable=self.x2).pack(side=tk.LEFT, padx=5, pady=5)# 商品名称输入框

        # 商品单价输入框
        l3 = Label(self.form_frame, text="商品单价:")
        l3.pack(side=tk.LEFT, padx=5, pady=5)
        tk.Entry(self.form_frame, textvariable=self.x3).pack(side=tk.LEFT, padx=5, pady=5) # 商品单价输入框

        # 购买者编号输入框
        l4 = Label(self.form_frame, text="购买者编号:")
        l4.pack(side=tk.LEFT, padx=5, pady=5)
        tk.Entry(self.form_frame, textvariable=self.x4).pack(side=tk.LEFT, padx=5, pady=5)# 购买者编号输入框

        # 商品介绍输入框
        l5 = Label(self.form_frame, text="商品介绍:")
        l5.pack(side=tk.LEFT, padx=5, pady=5)
        tk.Entry(self.form_frame, textvariable=self.x5).pack(side=tk.LEFT, padx=5, pady=5)# 商品备注输入框

        # 备注输入框
        l6 = Label(self.form_frame, text="备注:")
        l6.pack(side=tk.LEFT, padx=5, pady=5)
        tk.Entry(self.form_frame, textvariable=self.x6).pack(side=tk.LEFT, padx=5, pady=5)

        # .建立数据库的连接.
    def setup_database(self):
            self.db = mysql.connector.connect(
                host="localhost",
                user="root",
                password="AAA666111",
                database="test4"
            )
            self.cursor = self.db.cursor()

    def query_goods(self):
            self.listbox.delete(0, tk.END)  # 清空列表框内容
            self.cursor.execute("SELECT * FROM tb_good")
            rows = self.cursor.fetchall()
            for row in rows:
                self.listbox.insert(tk.END, f"ID: {row[0]}, Name: {row[1]}")  # 假设只有ID和Name

    def add_goods(self):
        if not self.x1.get() or not self.x2.get():
            messagebox.showerror("错误", "商品编号和商品名称不能为空！")
            return
        try:
            sql = "INSERT INTO goods (Gid, Gname, GPay, stock) VALUES (%s, %s, %s, %s)"
            val = (self.x1.get(), self.x2.get(), self.x3.get(), self.x4.get())
            self.cursor.execute(sql, val)
            self.db.commit()
            messagebox.showinfo("成功", "商品添加成功！")
        except mysql.connector.Error as e:
            messagebox.showerror("错误", f"添加商品时出错: {e}")

    def delete_goods(self):
        selected_index = self.listbox.curselection()
        if not selected_index:
            messagebox.showerror("错误", "请选择要删除的商品！")
            return
        selected_id = int(self.listbox.get(selected_index[0]).split(', ')[0].split(': ')[1])
        try:
            sql = "DELETE FROM goods WHERE Gid = %s"
            self.cursor.execute(sql, (selected_id,))
            self.db.commit()
            messagebox.showinfo("成功", "商品删除成功！")
            self.query_goods()  # 重新查询商品列表
        except mysql.connector.Error as e:
            messagebox.showerror("错误", f"删除商品时出错: {e}")

    def update_goods(self):
        selected_index = self.listbox.curselection()
        if not selected_index:
            messagebox.showerror("错误", "请选择要修改的商品！")
            return
        selected_id = int(self.listbox.get(selected_index[0]).split(', ')[0].split(': ')[1])
        if not self.x1.get() or not self.x2.get():
            messagebox.showerror("错误", "商品编号和商品名称不能为空！")
            return
        try:
            sql = "UPDATE goods SET GName=%s, GPay=%s, Cid=%s WHERE Gid=%s"
            val = (self.x2.get(), self.x3.get(), self.x4.get(), selected_id)
            self.cursor.execute(sql, val)
            self.db.commit()
            messagebox.showinfo("成功", "商品修改成功！")
            self.query_goods()  # 重新查询商品列表
        except mysql.connector.Error as e:
            messagebox.showerror("错误", f"修改商品时出错: {e}")

    # 其他的初始化方法和设置entryframe的方法...

    # 其他的方法，如setup_database, query_goods, add_goods, delete_goods, update_goods等，这里省略了实现细节

    def query_goods(self):
        self.listbox.delete(0, tk.END)  # 清空列表框内容
        self.cursor.execute("SELECT * FROM tb_good")
        rows = self.cursor.fetchall()
        for row in rows:
            self.listbox.insert(tk.END, f"ID: {row[0]}, Name: {row[1]}")  # 假设只有ID和Name

    def add_goods(self):
        if not self.x1.get() or not self.x2.get():
            messagebox.showerror("错误", "商品编号和商品名称不能为空！")
        return
        try:
            sql = "INSERT INTO goods (Gid, Gname, GPay, Cid) VALUES (%s, %s, %s, %s)"
            val = (self.x1.get(), self.x2.get(), self.x3.get(), self.x4.get())
            self.cursor.execute(sql, val)
            self.db.commit()
            messagebox.showinfo("成功", "商品添加成功！")
        except mysql.connector.Error as e:
            messagebox.showerror("错误", f"添加商品时出错: {e}")

    def delete_goods(self):
        selected_index = self.listbox.curselection()
        if not selected_index:
            messagebox.showerror("错误", "请选择要删除的商品！")
            return
        selected_id = int(self.listbox.get(selected_index[0]).split(', ')[0].split(': ')[1])
        try:
            sql = "DELETE FROM goods WHERE Gid = %s"
            self.cursor.execute(sql, (selected_id,))
            self.db.commit()
            messagebox.showinfo("成功", "商品删除成功！")
            self.query_goods()  # 重新查询商品列表
        except mysql.connector.Error as e:
            messagebox.showerror("错误", f"删除商品时出错: {e}")

    def update_goods(self):
        selected_index = self.listbox.curselection()
        if not selected_index:
            messagebox.showerror("错误", "请选择要修改的商品！")
            return
        selected_id = int(self.listbox.get(selected_index[0]).split(', ')[0].split(': ')[1])
        if not self.x1.get() or not self.x2.get():
            messagebox.showerror("错误", "商品编号和商品名称不能为空！")
            return
        try:
            sql = "UPDATE goods SET GName=%s, GPay=%s, Cid=%s WHERE Gid=%s"
            val = (self.x2.get(), self.x3.get(), self.x4.get(), selected_id)
            self.cursor.execute(sql, val)
            self.db.commit()
            messagebox.showinfo("成功", "商品修改成功！")
            self.query_goods()  # 重新查询商品列表
        except mysql.connector.Error as e:
            messagebox.showerror("错误", f"修改商品时出错: {e}")

            # 其他的初始化方法和设置entryframe的方法...

    def __del__(self):
        if self.db:
            self.db.close()
        # 如果从其他地方（比如主窗口）启动GoodsManagement类，可以这样调用：
# gm = GoodsManagement()